package middlewarex

import (
	"net/http/httputil"

	"github.com/gin-gonic/gin"

	"zhonghui/console/warehouse/logx"
	"zhonghui/console/warehouse/respx"
)

// Recovery gin框架panic恢复中间件
func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				httpRequest, _ := httputil.DumpRequest(c.Request, false)
				clientIp := c.ClientIP()
				requestId := c.GetString("RequestId")

				logx.Zap().Errorw("recovery from panic",
					"request_id", c.GetString("RequestId"),
					"url", c.Request.URL.String(),
					"user_agent", c.Request.UserAgent(),
					"error", err,
					"request_id", requestId,
					"client_ip", clientIp,
					"request", string(httpRequest),
				)

				respx.Alert(c, "网站开小差了请稍后再试")
				c.Abort()
			}
		}()
		c.Next()
	}
}
